package com.nowcoder.controller;

import com.nowcoder.annotation.LoginRequired;
import com.nowcoder.entity.User;
import com.nowcoder.service.FollowService;
import com.nowcoder.service.LikeService;
import com.nowcoder.service.UserService;
import com.nowcoder.utils.CommunityConstant;
import com.nowcoder.utils.CommunityUtil;
import com.nowcoder.utils.HostHolder;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@Controller
@RequestMapping("/user")
public class UserController implements CommunityConstant {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    LikeService likeService;

    @Autowired
    FollowService followService;

    @Value("${community.path.upload}")
    private String uploadPath;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${qiniu.sk}")
    String sk;

    @Value("${qiniu.ak}")
    String ak;

    @Value("${qiniu.bucket.header}")
    String headerBucketName;

    @Value("${qiniu.url.header}")
    String headerUrlName;

    @Autowired
    private UserService userService;

    @GetMapping("/header/{filename}")
    public void getHeader(HttpServletResponse response, @PathVariable("filename") String fileName) {
        // 服务器存放的路径
        String filePath = uploadPath + "/" + fileName;
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(filePath);
            ServletOutputStream outputStream =  response.getOutputStream();
            int len = 0;
            byte[] bytes = new byte[1024];
            while( (len = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
        } catch (IOException e) {
            logger.error("下载文件失败", e.getMessage());
        }
    }

    @LoginRequired
    @GetMapping("/setting")
    public String getSettingPage(Model model) {
        // 生成上传凭证 -> 不会有缓存
        String fileName = CommunityUtil.generateUUID();
        // 设置期待的返回信息
        StringMap policy = new StringMap();
        policy.put("returnBody", CommunityUtil.getJSONString(0));
        // 生成上传凭证
        Auth auth = Auth.create(ak, sk);
        String uploadToken = auth.uploadToken(headerBucketName, fileName, 3600, policy);
        model.addAttribute("uploadToken", uploadToken);
        model.addAttribute("fileName", fileName);
        return "/site/setting";
    }
    // 更新头像路径
    @PostMapping("/header/url")
    @ResponseBody
    public String updateHeaderUrl(String fileName) {
        if(StringUtils.isBlank(fileName)) {
            return CommunityUtil.getJSONString(1, "文件名不能为空");
        }
        String url = headerUrlName + "/" + fileName;
        userService.updateHeader(HostHolder.getUser().getId(), url);
        return CommunityUtil.getJSONString(0);
    }

    @LoginRequired
    @PostMapping("/update_password")
    public String updatePassword(String originPassword, String newPassword, Model model) {
        User user = HostHolder.getUser();
        if(user == null) {
            model.addAttribute("password_error", "用户不存在");
            return "/site/setting";
        }

        originPassword = originPassword + user.getSalt();
        originPassword = DigestUtils.md5DigestAsHex(originPassword.getBytes());
        String password = user.getPassword();
        if(! password.equals(originPassword)) {
            model.addAttribute("password_error", "输入的密码不正确");
            return "/site/setting";
        }
        newPassword = newPassword + user.getSalt();
        newPassword = DigestUtils.md5DigestAsHex(newPassword.getBytes());
        int result = userService.updatePassword(user.getId(), newPassword);
        if(result == 0) {
            model.addAttribute("password_error", "更新失败");
            return "/site/setting";
        }
        model.addAttribute("password_error", "密码更新成功");
        return "/site/setting";
    }

    @Deprecated
    @LoginRequired
    @PostMapping("/upload")
    public String uploadHeader(MultipartFile headerImage, Model model) {
        if(headerImage == null) {
            model.addAttribute("error", "你还没有选择图片");
            return "/site/setting";
        }
        String filename = headerImage.getOriginalFilename();
        String suffix = filename.substring(filename.lastIndexOf('.'));

        if(StringUtils.isBlank(suffix)) {
            model.addAttribute("error", "文件的格式不正确");
            return "/site/setting";
        }

        filename = CommunityUtil.generateUUID() + suffix;
        File dest = new File(uploadPath + "/" + filename);
        try {
            headerImage.transferTo(dest);
        } catch (IOException e) {
            logger.error("上传文件失败" + e.getMessage());
            throw new RuntimeException("上传文件失败", e);
        }
        String headerUrl = domain + "/user/header/" + filename;
        int userId = HostHolder.getUser().getId();
        userService.updateHeader(userId, headerUrl);
        return "redirect:/index";
    }

    @GetMapping("/profile/{userId}")
    public String getProfilePage(@PathVariable("userId") int userId, Model model) {
        User user = userService.findUserById(userId);
        if(user == null) {
            throw new IllegalArgumentException("用户不存在");
        }
        model.addAttribute("user", user);

        // 点赞数
        int likeCount = likeService.findUserLikeCount(userId);
        model.addAttribute("likeCount", likeCount);

        // 关注数
        long followeeCount = followService.findFolloweeCount(userId, ENTITY_TYPE_USER);
        model.addAttribute("followeeCount", followeeCount);
        // 粉丝数
        long followerCount = followService.findFollowerCount(userId, ENTITY_TYPE_USER);
        model.addAttribute("followerCount", followerCount);
        // 是否关注
        boolean hasFollowed = false;
        if(HostHolder.getUser() != null) {
            hasFollowed = followService.hasFollowed(HostHolder.getUser().getId(), ENTITY_TYPE_USER, userId);
            System.out.println("hasFollowed" + hasFollowed);
        }
        model.addAttribute("hasFollowed", hasFollowed);

        return "/site/profile";
    }
}










